package com.txm.task;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * Created by t on 2016/5/10.
 */
@Configuration
@EnableScheduling
public class Task {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成最近一周的访问量
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void pv() {
        redisTemplate.boundListOps("weekPV").leftPop();
        redisTemplate.boundListOps("weekPV").rightPush(Integer.valueOf(redisTemplate.opsForValue().get("operatingSystemTotal")) - Integer.valueOf(redisTemplate.opsForValue().get("PV")) + "");
        redisTemplate.boundValueOps("PV").set(redisTemplate.opsForValue().get("operatingSystemTotal"));
    }

    /**
     * 删除过期的日历
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void work() throws ParseException {
        List<String> list = redisTemplate.boundListOps("calendar").range(0, redisTemplate.boundListOps("calendar").size());
        for (int i = 0; i < list.size(); i++) {
            Map parse = JSON.parseObject(list.get(i), Map.class);
            Long end = Long.valueOf(parse.get("end").toString());
            if (end < System.currentTimeMillis())
                redisTemplate.boundListOps("calendar").remove(i, list.get(i));
        }


    }

}
